package com.sunshine.lnuplus.model.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = [User::class, Lesson::class, CountDown::class], version = 2, exportSchema = false)
abstract class TimetableDatabase : RoomDatabase() {
    abstract val timetableDao: TimetableDao?

    companion object {
        private var timetableDatabase: TimetableDatabase? = null
        @Synchronized
        fun getDatabase(context: Context): TimetableDatabase {
            if (timetableDatabase == null) {
                timetableDatabase = Room.databaseBuilder(context.applicationContext, TimetableDatabase::class.java, "timetable.db")
                    .allowMainThreadQueries()
                    .addMigrations(Migration1_2)
                    .build()
            }
            return timetableDatabase!!
        }

        private val Migration1_2 = object : Migration(1,2){
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Lesson ADD COLUMN startTime TEXT NOT NULL DEFAULT \"\"")
                database.execSQL("ALTER TABLE Lesson ADD COLUMN endTime TEXT NOT NULL DEFAULT \"\"")
            }
        }
    }
}